<template>
  <view class="change-password">
    <sar-divider>修改密码</sar-divider>

    <gi-form ref="pwdFormRef" v-model="pwdFormData" :columns="pwdFormColumns"></gi-form>

    <view class="form-actions">
      <sar-button theme="primary" @click="handlePwdSubmit">修改密码</sar-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import type { UserPasswordUpdateReq } from '@/apis/system/type'
import type { ColumnItem, GiFormInstance } from '@/components/gi-form/type'
import { resetUserPwd } from '@/apis/system/user'
import { useUserStore } from '@/store'

const userStore = useUserStore()
const pwdFormRef = ref<GiFormInstance>()

// 密码表单数据
const pwdFormData = reactive<UserPasswordUpdateReq>({
  oldPassword: '',
  newPassword: '',
})

// 密码表单列配置
const pwdFormColumns = computed(() => [
  {
    type: 'input',
    label: '当前密码',
    field: 'oldPassword',
    props: {
      type: 'password',
      placeholder: '请输入当前密码',
    },
    rules: [
      { required: true, message: '请输入当前密码', trigger: 'blur' },
    ],
  },
  {
    type: 'input',
    label: '新密码',
    field: 'newPassword',
    rules: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
    ],
    props: {
      type: 'password',
      placeholder: '请输入新密码',
    },
  },
] as ColumnItem[])

// 提交密码修改
async function handlePwdSubmit() {
  try {
    await pwdFormRef.value?.formRef.validate()
    const userId = userStore.userInfo?.id
    if (!userId) {
      uni.showToast({
        title: '用户ID不存在',
        icon: 'none',
      })
      return
    }

    // 调用重置密码接口
    const res = await resetUserPwd(pwdFormData, userId)
    if (res.success) {
      uni.showToast({
        title: '密码修改成功',
        icon: 'success',
      })
      // 清空密码表单
      pwdFormData.oldPassword = ''
      pwdFormData.newPassword = ''
    }
    else {
      uni.showToast({
        title: res.msg || '密码修改失败',
        icon: 'none',
      })
    }
  }
  catch (error) {
    console.error('表单验证失败', error)
  }
}
</script>

<style lang="scss" scoped>
.change-password {
  padding: 20px;
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.sar-divider) {
  margin: 30px 0;
}
</style>
